<template>
    <div class="disciple-page">
        <div class="page-header">
            <div class="title-area">
                <h2>弟子总览</h2>
                <span class="sub-title">共 {{ disciples.length }} 名弟子</span>
            </div>
            <div class="toolbar">
                <span class="filter-label">搜索</span>
                <el-input v-model="searchKeyword" class="search-input" placeholder="按姓名 / 赐号进行模糊搜索" clearable
                    :prefix-icon="Search" />

                <span class="filter-label">分数显示</span>
                <el-select v-model="viewScoreType" class="sort-select" placeholder="显示分数">
                    <el-option label="总积分" :value="0" />
                    <el-option label="山长积分" :value="1" />
                    <el-option label="师门积分" :value="2" />
                </el-select>

                <span class="filter-label">排序条件</span>
                <el-select v-model="sortField" class="sort-select" placeholder="排序字段">
                    <el-option label="总积分" value="score" />
                    <el-option label="星级" value="star" />
                </el-select>

                <el-radio-group v-model="sortOrder" class="order-group" style="margin-right: 20px">
                    <el-radio-button label="asc">
                        <el-icon>
                            <ArrowUp />
                        </el-icon>
                        升序
                    </el-radio-button>
                    <el-radio-button label="desc">
                        <el-icon>
                            <ArrowDown />
                        </el-icon>
                        降序
                    </el-radio-button>
                </el-radio-group>

                <el-button type="primary" :icon="Plus" @click="openAddDialog">
                    添加弟子
                </el-button>

                <el-button type="warning" :icon="RefreshLeft" :disabled="disciples.length === 0"
                    @click="openResetAllDialog">
                    清空弟子得分数据
                </el-button>

                <el-button type="danger" :icon="Delete" class="delete-all-btn" :disabled="disciples.length === 0"
                    @click="openDeleteAllDialog">
                    一键删除所有弟子
                </el-button>
            </div>
        </div>

        <div v-if="displayedDisciples.length > 0" class="card-grid">
            <el-card v-for="disciple in displayedDisciples" :key="disciple.id" class="disciple-card" shadow="hover" @click="toDetailPage(disciple as Disciple)">
                <div class="card-header">
                    <div class="avatar">
                        {{ disciple.name?.charAt(0) || disciple.code?.charAt(0) }}
                    </div>
                    <div class="base-info">
                        <div class="name-row">
                            <span class="name">{{ disciple.name }}</span>
                            <span class="code">({{ disciple.code }})</span>
                        </div>
                        <div class="star-row">
                            <el-icon class="star-icon">
                                <StarFilled />
                            </el-icon>
                            <span class="star-value">{{ disciple.star }}</span>
                            <span class="star-label">星级</span>
                        </div>
                    </div>
                    <div class="more-actions" @click.stop>
                        <el-dropdown trigger="click">
                            <span class="more-trigger">
                                <el-icon>
                                    <MoreFilled />
                                </el-icon>
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item @click.stop="openEditDialog(disciple as Disciple)">
                                        <el-icon>
                                            <Edit />
                                        </el-icon>
                                        <span>编辑</span>
                                    </el-dropdown-item>
                                    <el-dropdown-item @click.stop="openDeleteDialog(disciple as Disciple)">
                                        <span class="danger-action">
                                            <el-icon>
                                                <Delete />
                                            </el-icon>
                                            <span>删除</span>
                                        </span>
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </div>
                </div>

                <div class="card-body">
                    <div class="score-block">
                        <span class="score-value" v-if="viewScoreType == 0">
                            {{ getDiscipleScore(disciple as Disciple) }} 
                        </span>
                        <span class="score-label" v-if="viewScoreType == 0">总积分</span>
                        <span class="score-value" v-if="viewScoreType == 1">
                            {{ disciple.getLeaderBonusCappedTotal() }} 
                        </span>
                        <span class="score-label" v-if="viewScoreType == 1">山长积分</span>
                        <span class="score-value" v-if="viewScoreType == 2">
                            {{ disciple.getSectBonusCappedTotal() }} 
                        </span>
                        <span class="score-label" v-if="viewScoreType == 2">师门积分</span>
                    </div>
                </div>
            </el-card>
        </div>

        <div v-else class="empty-state">
            <el-empty description="暂无弟子数据，请先在其他页面添加弟子。" />
        </div>

        <!-- 编辑弟子弹窗 -->
        <el-dialog v-model="editDialogVisible" :title="editForm.id ? '编辑弟子' : '添加弟子'" width="480px">
            <el-form :model="editForm" label-width="80px">
                <el-form-item label="姓名">
                    <el-input v-model="editForm.name" placeholder="请输入弟子姓名" />
                </el-form-item>
                <el-form-item label="赐号">
                    <el-input v-model="editForm.code" placeholder="请输入弟子赐号" />
                </el-form-item>
                <el-form-item label="星级">
                    <el-input-number v-model="editForm.star" :min="0" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取消</el-button>
                    <el-button type="primary" v-if="editForm.id" @click="confirmEdit">保存</el-button>
                    <el-button type="primary" v-else @click="confirmAdd">添加</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 一键删除所有弟子弹窗 -->
        <el-dialog v-model="deleteAllDialogVisible" title="一键删除所有弟子" width="480px">
            <div class="warning-text">
                <p>此操作将删除当前所有弟子记录。</p>
                <p class="strong">
                    操作不可撤销，请务必确认后再继续！
                </p>
                <p class="countdown" v-if="deleteAllCountdown > 0">
                    请等待 {{ deleteAllCountdown }} 秒后才能点击确认按钮。
                </p>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="closeDeleteAllDialog" :disabled="isDeletingAll">
                        取消
                    </el-button>
                    <el-button type="danger" :disabled="isDeleteAllConfirmDisabled || isDeletingAll"
                        :loading="isDeletingAll" @click="confirmDeleteAll">
                        {{ isDeleteAllConfirmDisabled ? `确认删除（${deleteAllCountdown}s）` : '确认删除所有弟子' }}
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import {
    ArrowUp,
    ArrowDown,
    Delete,
    Edit,
    InfoFilled,
    MoreFilled,
    Search,
    StarFilled,
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { DiscipleService } from '@/service/DiscipleService';
import { Disciple } from '@/domain/Disciple';
import { useRouter } from 'vue-router';
import { Plus, RefreshLeft } from '@element-plus/icons-vue';
import { DataService } from '@/service/DataService';

type SortField = 'nameInitial' | 'codeInitial' | 'score' | 'star';
type SortOrder = 'asc' | 'desc';

const disciples = ref<Disciple[]>([]);
const searchKeyword = ref('');
const sortField = ref<SortField>('score');
const sortOrder = ref<SortOrder>('desc');
const router = useRouter();
const viewScoreType = ref<number>(0);

// 编辑弹窗
const editDialogVisible = ref(false);
const editForm = ref<{
    id?: string | null;
    name: string;
    code: string;
    star: number;
}>({
    id: '',
    name: '',
    code: '',
    star: 0,
});

// 一键删除弹窗
const deleteAllDialogVisible = ref(false);
const deleteAllCountdown = ref(5);
const isDeleteAllConfirmDisabled = ref(true);
const isDeletingAll = ref(false);
let deleteAllTimer: number | null = null;

/**
 * 加载所有弟子数据
 */
const loadDisciples = () => {
    const data = DiscipleService.getAllDisciple();
    disciples.value = data.map((d) => d as Disciple);
};

/**
 * 获取弟子当前周期总积分
 * @param disciple 弟子对象
 */
const getDiscipleScore = (disciple: Disciple): number => {
    if (typeof disciple.getCurrentPeriodCappedTotalScore === 'function') {
        return disciple.getCurrentPeriodCappedTotalScore();
    }
    if (typeof disciple.getCurrentPeriodTotalScore === 'function') {
        return disciple.getCurrentPeriodTotalScore();
    }
    return disciple.totalScore || 0;
};

/**
 * 排序计算函数
 */
const displayedDisciples = computed(() => {
    const keyword = searchKeyword.value.trim().toLowerCase();

    let list = disciples.value.filter((d) => {
        if (!keyword) return true;
        const name = d.name ? d.name.toLowerCase() : '';
        const code = d.code ? d.code.toLowerCase() : '';
        return name.includes(keyword) || code.includes(keyword);
    });

    const multiplier = sortOrder.value === 'asc' ? 1 : -1;

    list = list.slice().sort((a, b) => {
        if (sortField.value === 'score') {
            return (getDiscipleScore(a as Disciple) - getDiscipleScore(b as Disciple)) * multiplier;
        }
        if (sortField.value === 'star') {
            return ((a.star || 0) - (b.star || 0)) * multiplier;
        }
        return 0;
    });

    return list;
});

/**
 * 打开添加弟子弹窗
 */
const openAddDialog = () => {
    editForm.value = {
        id: null,
        name: '',
        code: '',
        star: 0,
    };
    editDialogVisible.value = true;
};

/**
 * 打开编辑弟子信息弹窗
 * @param disciple 弟子信息
 */
const openEditDialog = (disciple: Disciple) => {
    editForm.value = {
        id: disciple.id,
        name: disciple.name,
        code: disciple.code,
        star: disciple.star ?? 0,
    };
    editDialogVisible.value = true;
};

/**
 * 确认添加弟子
 */
const confirmAdd = () => {
    const { name, code, star } = editForm.value;
    if (!name.trim() || !code.trim()) {
        ElMessage.error('姓名和赐号不能为空');
        return;
    }

    const newDisciple = new Disciple(code, name, 0);
    newDisciple.star = star ?? 0;

    const result = DiscipleService.addDisciple(newDisciple);
    if (result.success) {
        ElMessage.success('弟子添加成功');
        editDialogVisible.value = false;
        loadDisciples();
    } else {
        ElMessage.error(result.message || '弟子添加失败');
    }
};

/**
 * 确认编辑弟子信息
 */
const confirmEdit = () => {
    const { id, name, code, star } = editForm.value;
    if (!name.trim() || !code.trim()) {
        ElMessage.error('姓名和赐号不能为空');
        return;
    }

    if (!id) {
        ElMessage.error('无效的弟子ID');
        return;
    }

    const updated = new Disciple(code, name, 0);
    updated.id = id;
    updated.star = star ?? 0;

    const result = DiscipleService.editDisciple(updated);
    if (result.success) {
        ElMessage.success('弟子信息更新成功');
        editDialogVisible.value = false;
        loadDisciples();
    } else {
        ElMessage.error(result.message || '弟子信息更新失败');
    }
};

/**
 * 打开删除单个弟子弹窗
 * @param disciple 弟子对象
 */
const openDeleteDialog = (disciple: Disciple) => {
    ElMessageBox.confirm(
        `确定要删除弟子 <strong>${disciple.name} (${disciple.code})</strong> 吗？此操作不可撤销！`,
        '删除弟子',
        {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true,
        }
    )
        .then(() => {
            deleteSingleDisciple(disciple);
        })
        .catch(() => {
            // 取消删除
        });
}

/**
 * 删除单个弟子
 * @param disciple 弟子对象
 */
const deleteSingleDisciple = (disciple: Disciple) => {
    const result = DiscipleService.deleteDisciple(disciple.id);
    if (result.success) {
        ElMessage.success('弟子已删除');
        loadDisciples();
    } else {
        ElMessage.error(result.message || '删除弟子失败');
    }
};

/**
 * 重置所有弟子得分数据
 */
const openResetAllDialog = () => {
    ElMessageBox.confirm(
        `确定要清空所有弟子的得分数据吗？此操作不可撤销！`,
        '清空弟子得分数据',
        {
            confirmButtonText: '清空',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            DataService.resetData();
            ElMessage.success('已清空所有弟子的得分数据');
            loadDisciples();
        })
        .catch(() => {
            // 取消操作
        });
};

/**
 * 打开一键删除所有弟子弹窗
 */
const openDeleteAllDialog = () => {
    if (!disciples.value.length) return;
    deleteAllDialogVisible.value = true;
    deleteAllCountdown.value = 5;
    isDeleteAllConfirmDisabled.value = true;

    if (deleteAllTimer) {
        window.clearInterval(deleteAllTimer);
    }

    deleteAllTimer = window.setInterval(() => {
        if (deleteAllCountdown.value <= 1) {
            isDeleteAllConfirmDisabled.value = false;
            deleteAllCountdown.value = 0;
            if (deleteAllTimer) {
                window.clearInterval(deleteAllTimer);
                deleteAllTimer = null;
            }
        } else {
            deleteAllCountdown.value -= 1;
        }
    }, 1000);
};

/**
 * 关闭一键删除所有弟子弹窗
 */
const closeDeleteAllDialog = () => {
    deleteAllDialogVisible.value = false;
    if (deleteAllTimer) {
        window.clearInterval(deleteAllTimer);
        deleteAllTimer = null;
    }
};

/**
 * 确认一键删除所有弟子
 */
const confirmDeleteAll = () => {
    if (isDeleteAllConfirmDisabled.value || isDeletingAll.value) return;
    isDeletingAll.value = true;
    try {
        const current = [...disciples.value];
        current.forEach((d) => {
            DiscipleService.deleteDisciple(d.id);
        });
        ElMessage.success('已删除所有弟子');
        loadDisciples();
        deleteAllDialogVisible.value = false;
    } catch (e) {
        ElMessage.error('删除所有弟子时发生错误');
    } finally {
        isDeletingAll.value = false;
        if (deleteAllTimer) {
            window.clearInterval(deleteAllTimer);
            deleteAllTimer = null;
        }
    }
};

onMounted(() => {
    loadDisciples();
});

onBeforeUnmount(() => {
    if (deleteAllTimer) {
        window.clearInterval(deleteAllTimer);
        deleteAllTimer = null;
    }
});


/**
 * 跳转到弟子详情页面
 * @param disciple 弟子对象
 */
const toDetailPage = (disciple: Disciple) => {
    sessionStorage.setItem("routerParam", JSON.stringify(disciple));
    router.push({ path: '/disciple/detail' })
};
</script>

<style scoped>
.disciple-page {
    padding: 20px 24px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 80px);
    box-sizing: border-box;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 18px;
}

.title-area {
    display: flex;
    flex-direction: column;
}

.title-area h2 {
    margin: 0;
    font-size: 20px;
    color: #303133;
}

.sub-title {
    margin-top: 4px;
    font-size: 13px;
    color: #909399;
}

.toolbar {
    display: flex;
    align-items: center;
    gap: 12px;
}

.search-input {
    width: 260px;
}

.sort-select {
    width: 140px;
}

.order-group :deep(.el-radio-button__inner) {
    padding: 6px 12px;
}

.delete-all-btn {
    margin-left: 8px;
}

.card-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
    gap: 16px;
}

.disciple-card {
    border-radius: 10px;
    overflow: hidden;
}

.card-header {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
}

.avatar {
    width: 46px;
    height: 46px;
    border-radius: 50%;
    background: linear-gradient(135deg, #409eff, #79bbff);
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    font-size: 20px;
    margin-right: 12px;
    flex-shrink: 0;
}

.base-info {
    flex: 1;
}

.name-row {
    display: flex;
    align-items: baseline;
    gap: 4px;
    margin-bottom: 4px;
}

.name {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
}

.code {
    font-size: 13px;
    color: #909399;
}

.star-row {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 13px;
    color: #909399;
}

.star-icon {
    color: #e6a23c;
}

.star-value {
    font-weight: 600;
    color: #e6a23c;
}

.star-label {
    color: #909399;
}

.more-actions {
    margin-left: 8px;
}

.more-trigger {
    cursor: pointer;
    color: #909399;
    display: inline-flex;
    align-items: center;
}

.more-trigger:hover {
    color: #606266;
}

.danger-action {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    color: #f56c6c;
}

.card-body {
    margin-top: 4px;
}

.score-block {
    background-color: #f5f7fa;
    border-radius: 6px;
    padding: 10px 12px;
    display: flex;
    /* flex-direction: column; */
}

.score-label {
    font-size: 12px;
    color: #909399;
    margin: 4px;
    margin-right: 12px;
    transform: translate(0, 4px);
}

.score-value {
    font-size: 20px;
    font-weight: 700;
    color: #409eff;
}

.empty-state {
    margin-top: 40px;
}

.warning-text {
    line-height: 1.6;
}

.warning-text .strong {
    color: #f56c6c;
    font-weight: 600;
}

.warning-text .countdown {
    margin-top: 6px;
    color: #e6a23c;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
}

.filter-label {
    font-size: 14px;
    color: #606266;
    margin-right: 0;
    margin-left: 20px;
}

@media (max-width: 768px) {
    .page-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }

    .toolbar {
        flex-wrap: wrap;
    }

    .card-grid {
        grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    }
}
</style>
